package com.liujit.pay.wx.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.liujit.pay.common.domain.result.PayResult;
import com.liujit.pay.common.enums.RequestMethod;
import com.liujit.pay.common.enums.SignType;
import com.liujit.pay.common.util.PayUtil;
import com.liujit.pay.wx.domain.params.order.APPOrderParam;
import com.liujit.pay.wx.domain.params.order.H5OrderParam;
import com.liujit.pay.wx.domain.params.order.JSAPIOrderParam;
import com.liujit.pay.wx.domain.params.order.NativeOrderParam;
import com.liujit.pay.wx.domain.params.refunds.RefundsParam;
import com.liujit.pay.wx.domain.result.*;
import com.liujit.pay.wx.enums.PayApi;
import com.liujit.pay.wx.enums.ReturnCode;
import com.liujit.pay.wx.kit.HttpKit;
import com.liujit.pay.wx.kit.RefundsKit;
import com.liujit.pay.wx.kit.WxPayKit;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 微信退款相关接口
 * @author: liujun
 * @create: 2021-02-20 11:40
 */
public class WxRefundsApi {

    /**
     * 退款
     *
     * @param param
     * @return
     */
    public static PayResult refund(RefundsParam param) {
        // 请求参数
        String body = param.toJSONString();
        // 发送请求
        String resp = refund(body, PayApi.REFUNDS, param.getMchId(), param.getKeyPath(), param.getSerialNo());
        JSONObject respJson = JSONUtil.parseObj(resp);
        ReturnCode returnCode = ReturnCode.getReturnCode(respJson.getStr("code"));
        if (returnCode != null) {
            return new PayResult(returnCode.getCode(), returnCode.getMessage());
        }
        RefundsResult result = RefundsKit.getResult(respJson);
        return new PayResult(result);
    }

    /**
     * 发送请求
     *
     * @param body     请求参数
     * @param payApi   请求地址
     * @param mchId
     * @param keyPath
     * @param serialNo
     * @return
     */
    private static String refund(String body, PayApi payApi, String mchId, String keyPath, String serialNo) {
        // 获取请求签名
        String authorization = WxPayKit.buildAuthorization(RequestMethod.POST, payApi.getApi(), mchId, serialNo, keyPath, body);
        // 发送请求
        return HttpKit.post(WxPayKit.getReqUrl(payApi), authorization, serialNo, body);
    }
}
